<?php
namespace common\models\userFund;

use common\models\Common;
use common\models\Functions;
use common\models\im\Im;
use common\models\Status;
use common\models\user\User;
use common\services\pay\iosPay\IosPay;
use Yii;
use yii\base\Exception;

/**
 * This is the model class for table "goods".
 *
 * @property int $id
 * @property string $name
 */
class UserRechargeOrder extends Common
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%user_recharge}}';
    }

    public function getUser()
    {
        return $this->hasOne(User::className(), ['id' => 'user_id']);
    }

    public function _createOrderNumber() {
        do {
            $orderNumber = 'R'.date('YmdHi').Functions::generateCode(8);
            $exist = static::getOneByWhere(['order_number' => $orderNumber]);
        } while ($exist > 0);

        return $orderNumber;
    }

    // 校验充值
    public function checkRechargeConfig($money = 0) {
        $checkSetting = RechargeSetting::getOneByWhere(['money' => $money,'status' => Status::COMMON_RADIO_YES]);
        if (empty($checkSetting)) {
            throw new Exception('充值金额不合法');
        }

        $config = static::getCommonByKey(['recharge_start','recharge_end','recharge_switch']);
        if ($config['recharge_switch'] != Status::COMMON_RADIO_YES) {
            throw new Exception('充值通道已关闭');
        }

        $time = date('H:i');
        if ($time > $config['recharge_end'] || $time < $config['recharge_start']) {
            throw new Exception("充值时间为:{$config['recharge_start']} - {$config['recharge_end']}");
        }
    }


    /**
     * 内购支付
     * @param string $orderNumber
     * @param string $receiptData
     * @throws Exception
     */
    public function iosPay($orderNumber = '', $receiptData = "") {

        $verify = (new IosPay())->verifyPay($receiptData);
        if ($verify['status'] == 0) {
            $where['order_number'] = $orderNumber;
            $orderInfo = static::getOneByAndWhere($where);
            $userId = $orderInfo['user_id'];

            //1.判断该订单是否成功支付过
            if ($orderInfo['status'] == Status::RECHARGE_STATUS_DOING) {
                throw new Exception('该订单已经付过款');
            }

            //2.是否有内购过
            $isExist = static::getOneByWhere(['transaction_id' => $verify['transaction_id']],['id']);
            if ($isExist) {
                throw new Exception('该订单已经付过款');
            }
//            if ($orderInfo['buy_money'] !== $totalAmount * 100) {
//                throw new Exception('订单金额与实际金额不一致');
//            }

            $this->success($orderNumber, Status::PAY_WAY_IOS, $verify['pay_time'], $verify['transaction_id']);
        }

    }

    //支付成功
    public function success($orderNumber, $payWay, $payTime, $iosPayId = 0) {

        if (empty($orderNumber)) {
            throw new Exception('未知订单');
        }

        $orderInfo = static::getOneByWhere([
            'order_number' => $orderNumber,
        ]);

        if ($orderInfo['status'] != Status::RECHARGE_STATUS_DOING) {
            throw new Exception('该订单已经付过款');
        }


        //1.更改订单状态
        $data['status'] = Status::RECHARGE_STATUS_DONE;
        $data['success_time'] = $payTime ? $payTime : date('Y-m-d H:i:s');//支付时间
        $data['pay_way'] = $payWay;
        if ($payWay == Status::PAY_WAY_IOS) {
            $update['transaction_id'] = $iosPayId;
        }
        $res = static::updateData($data, ['order_number' => $orderNumber]);
        if ($res === false) {
            throw new Exception('支付失败');
        }

        // 余额信息
        UserMoneyLog::record(
            $orderInfo['user_id'],
            Status::PROP_TYPE_MONEY,
            Status::MONEY_LOG_TYPE_RECHARGE,
            floatval($orderInfo['money']),
            Status::MONEY_LOG_TYPE_MAP[Status::MONEY_LOG_TYPE_RECHARGE] ?? '',
            '充值成功，单号：【' . $orderNumber.'】',
            $orderInfo['id']
        );

        $userInfo = User::getOneByWhere(['id' => $orderInfo['user_id']],['id','tx_code']);

        // 发送IM信息
        $userMessage = [];
        $userMessage['message_type'] = (int) Status::MESSAGE_TYPE_USER_MONEY_MESSAGE;
        $userMessage['type'] = (int) Status::MESSAGE_TYPE_USER_MONEY_MESSAGE;
        $userMessage['title'] = "充值";
        $userMessage['money_title'] = "充值金额";
        $userMessage['money'] = (string) abs($orderInfo['money']);
        $userMessage['desc'] = "充值".$orderInfo['money']."元";
        $userMessage['mark'] = "你可以在钱包中查看相关记录";
        $userMessage['time'] = date('Y-m-d H:i:s');
        $config = static::getCommonByKey('money_user_id');
        (new Im()) -> sendUserMessage($userInfo['tx_code'], $userMessage, $config);

    }
}
